import csv
import os

import pymysql
import yaml

_DEFAULT_ENCODING_UTF8 = "utf-8"
_CHARACTER_COMMA = ","


class _PathHelper(object):
    """
    路径处理
    """
    # @staticmethod
    # def get_actual_path(current, filename):
    #     """
    #     获取绝对路径
    #     从项目根目录与执行文件的相对路径中获取绝对路径
    #     :param current: 当前文件的真实绝对路径
    #     :param filename: 被访问文件与当前文件的相对路径
    #     :return: 路径
    #     """
    #     file_path = os.path.dirname(current)
    #     abspath = os.path.abspath(os.path.join(file_path, filename))
    #     return abspath

    @staticmethod
    def get_actual_path(file):
        '''
        获取文件的绝对路径
        :param file: 文件在项目中所处的路径，格式如：'niushop22\\data\\login.csv'
        :return:
        '''
        # 以'\\'对输入的文件路径进行分割，取第一部分即项目名称
        project_name = file.split('\\')[0]
        # 以'项目名称'对获取的路径进行分割，取第一部分即项目所在的目录路径
        root_path = os.path.abspath(os.path.dirname(__file__)).split(project_name)[0]
        # 并接'项目所在的目录路径'和'文件的路径'，即文件的绝对路径
        file_path = root_path + file
        return file_path

    @staticmethod
    def file_is_exist(filename):
        """
        file is exist
        :param filename:
        :return:
        """
        return os.path.exists(filename)


class _CsvHelper(object):

    @staticmethod
    def read_as_list(f, encoding=_DEFAULT_ENCODING_UTF8):
        """
        读csv文件作为普通list
        :param f:
        :param encoding:
        :return:
        """
        data_ret = []
        with open(f, encoding=encoding, mode='r') as csv_file:
            csv_data = csv.reader(csv_file)
            for row in csv_data:
                data_ret.append(row)

        return data_ret

    @staticmethod
    def read_as_dict(f, encoding=_DEFAULT_ENCODING_UTF8):
        """
        读csv文件作为 OrderedDict List
        :param f:
        :param encoding:
        :return:
        """
        data_ret = []
        with open(f, encoding=encoding, mode='r') as csv_file:
            csv_dict = csv.DictReader(csv_file)
            for row in csv_dict:
                data_ret.append(row)

        return data_ret

    @staticmethod
    def read_as_dict2(file, encoding=_DEFAULT_ENCODING_UTF8):
        """
        读csv文件作为普通 Dict List
        :param file:
        :param encoding:
        :return:
        """
        data_ret = []
        file_path = _PathHelper().get_actual_path(file)
        with open(file_path, encoding=encoding, mode='r') as csv_file:
            csv_dict = csv.DictReader(csv_file)

            for row in csv_dict:
                row_dict = {}
                for key in row.keys():
                    row_dict[key] = row.get(key)
                data_ret.append(row_dict)

        return data_ret


class _DbHelper(object):
    """
    MySQ 数据库帮助类
    """

    # 使用方法
    # 1. 实例化对象
    # 2. 查询，得到结果
    # 3. 关闭对象
    """
    db_helper = MysqlDbHelper("localhost", 3306, 'root', '', 'tpshop2.0.5', "utf8")
    for i in range(10000):

        result = db_helper.execute("select * from tp_goods order by 1 desc limit 1000;")
        print("第%d次，结果是%r" % (i, result))

    db_helper.close()
    """

    connect = None

    def __init__(self, host, port, user, password, database, charset='utf-8'):
        """
        构造方法
        :param host: 数据库的主机地址
        :param port: 数据库的端口号
        :param user: 用户名
        :param password: 密码
        :param database: 选择的数据库
        :param charset: 字符集
        """
        self.connect = pymysql.connect(host=host, port=port,
                                       user=user, password=password,
                                       db=database, charset=charset)

    @staticmethod
    def read_sql(file, encoding=_DEFAULT_ENCODING_UTF8):
        """
        从 文件中读取 SQL 脚本
        :param file: 文件名 + 文件路径
        :param encoding:
        :return:
        """
        file_path = _PathHelper().get_actual_path(file)
        sql_file = open(file_path, "r", encoding=encoding)
        sql = sql_file.read()
        sql_file.close()
        return sql

    def query(self, sql):
        """
        执行 SQL 脚本查询并返回结果
        :param sql: 需要查询的 SQL 语句
        :return: 字典类型
            data 是数据，本身也是个字典类型
            count 是行数
        """
        cursor = self.connect.cursor()

        row_count = cursor.execute(sql)
        rows_data = cursor.fetchall()
        result = {
            "count": row_count,
            "data": rows_data
        }

        cursor.close()
        return result

    def execute(self, sql):
        """
        执行 SQL 脚本查询并返回结果
        :param sql: 需要查询的 SQL 语句
        :return: 字典类型
            data 是数据，本身也是个字典类型
            count 是行数
        """
        cursor = self.connect.cursor()

        cursor.execute(sql)

        self.connect.commit()

        cursor.close()

    def close(self):
        """
        关闭数据库连接
        :return:
        """
        self.connect.close()


class _YamlHelper(object):

    @staticmethod
    def get_config_as_dict(file):
        """
        获取所有配置 作为 Dict
        :param file: 
        :param f:
        :return:
        """
        file_path = _PathHelper().get_actual_path(file)
        with open(file_path, mode='r', encoding='utf8') as file_config:
            config_dict = yaml.load(file_config.read())
            return config_dict


class _JsonHelper(object):

    @classmethod
    def parse_json_dict_value(cls, json_dict, key, index=0, sub_key=None):
        """
        get json dict value
        :param json_dict:
        :param sub_key:
        :param key:
        :param index: 从 1 开始
        :return:
        """

        json_dict = cls._get_dict_value(json_dict, key)
        if index and isinstance(json_dict, list) and len(json_dict) >= index:
            json_dict = json_dict[index]

        if sub_key is not None:
            json_dict = cls._get_dict_value(json_dict, sub_key)

        return json_dict

    @classmethod
    def _get_dict_value(cls, json_dict, key):
        """
        parse dict value
        :param json_dict:
        :param key:
        :return:
        """
        keys = []
        if _CHARACTER_COMMA in key:
            keys = key.split(_CHARACTER_COMMA)
        else:
            keys.append(key.strip())

        if isinstance(json_dict, dict):
            for k in keys:
                k = k.strip()
                if k in json_dict.keys():
                    json_dict = json_dict[k]
                else:
                    break

        return json_dict
